/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.core.content.res.ResourcesCompat;

import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.contrack.RegisterContrack;
import com.srwl.mytx.contrack.UpdateUserInfoPresenterImpl;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.utils.StringUtil;
import com.srwl.mytx.utils.Utils;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.List;


/**
 * register screen
 */
public class UpdateUserInfoActivity extends BaseRegisterActivity<RegisterContrack.Presenter> implements RegisterContrack.View{
    private static final String TAG = "UpdateUserInfoActivity";
    private static final int PERMISSION_REQUEST_CODE = 0;

    private EditText et_name;
    private EditText et_phone;
    private EditText et_password;
    private Button btn_register;
    private ImageView iv_hide;
    private ImageView iv_show;



    String path = "";
    Bitmap bitmap;
    Button btn_sendMobileCode;
    EditText et_mobileCode;
    Context context;
    GaodeLocationClient location;
    private ProgressDialog progressDialog;
    List<Uri> selectedPhotos;
    private String phone;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_updatauserinfo);
//        Toolbar toolbar = findViewById(R.id.toolbar);
//        toolbar.setTitle("注册");
//        setSupportActionBar(toolbar);
        context = this;
        path = Helper.getInstance().getBasePath() + File.separator + getString(R.string.avatar_name);
        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);
        btn_sendMobileCode = findViewById(R.id.btn_send_mobile_code);
        et_mobileCode = findViewById(R.id.et_mobile_code);
        btn_register = findViewById(R.id.btn_register);
        iv_hide = findViewById(R.id.iv_hide);
        iv_show = findViewById(R.id.iv_show);

        initTextChangeListener();
        iv_hide.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.INVISIBLE);
                iv_show.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                et_password.setSelection(et_password.getText().length());

            }

        });
        iv_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.INVISIBLE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                et_password.setSelection(et_password.getText().length());
            }
        });
        btn_register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                updataUserInfo();
            }
        });
        btn_sendMobileCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = et_phone.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    et_phone.setHint("手机号不能为空");
                    Utils.editViewValueErrorAnimate(et_phone, context);
                    et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
                    return;
                }

                if (!Utils.checkMobileNum(phone)) {
                    showToast(btn_sendMobileCode, getString(R.string.phone_number_type_error));
                    et_phone.setTextColor(Color.RED);
                    Utils.editViewValueErrorAnimate(et_phone, context);
                    et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
                    return;
                }
                et_mobileCode.setText("");
                presenter.sendMobileCode(phone);
            }
        });

        initProgressDialog();
        //清空缓存中的用户数据
        //Helper.getInstance().removeLoginUserInfo();
    }

    private void initTextChangeListener() {
        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_name.getCurrentTextColor() == Color.RED) {
                    et_name.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String userName = StringUtil.checkUserName(s.toString());
//                if (isError) {
//                    et_name.setTextColor(Color.RED);
//                    showToast("姓名中含有特殊符号，请检查");
//                }

                if (!TextUtils.equals(userName, s.toString())) {
                    et_name.setText(userName);
                    Log.d(TAG, "afterTextChanged: " + userName);
                    if (!TextUtils.isEmpty(userName)) {
                        et_name.setSelection(userName.length());
                    }
                }
            }
        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_password.getCurrentTextColor() == Color.RED) {
                    et_password.setTextColor(getResources().getColor(R.color.text_black));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() > 20) {
                    s.delete(20, 21);
                }
                if (et_password.getText().length() >= 6) {
                    //检测密码强度
                    showToast(et_password, "密码强度：" + StringUtil.validatePassWord(et_password.getText().toString()));
                }
            }
        });

        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (et_password.getText().length() > 0 && et_password.getText().length() < 6) {
                        showToast(et_password, "密码长度少于6位");
                        et_password.setTextColor(Color.RED);
                    }
                }
            }
        });

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_phone.getCurrentTextColor() == Color.RED) {
                    et_phone.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_mobileCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_mobileCode.getCurrentTextColor() == Color.RED) {
                    et_mobileCode.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    RegisterContrack.Presenter initPresenter() {
        return new UpdateUserInfoPresenterImpl(this, this);
    }



    /**
     * 检测各输入项是否有值
     */
    public void updataUserInfo() {
        hideSoftKeyboard();
        String password = et_password.getText().toString().trim();
        String mobileCode = et_mobileCode.getText().toString().trim();
        phone = et_phone.getText().toString().trim();
        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Utils.editViewValueErrorAnimate(et_name, context);
            et_name.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (TextUtils.isEmpty(phone)) {
            et_phone.setHint("手机号不能为空");
            Utils.editViewValueErrorAnimate(et_phone, context);
            et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (!Utils.checkMobileNum(phone)) {
            showToast(btn_register, getString(R.string.phone_number_type_error));
            et_phone.setTextColor(Color.RED);
            Utils.editViewValueErrorAnimate(et_phone, context);
            et_phone.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (TextUtils.isEmpty(mobileCode)) {
            et_mobileCode.setHint("验证码不能为空");
            Utils.editViewValueErrorAnimate(et_mobileCode, context);
            et_mobileCode.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (TextUtils.isEmpty(password)) {
            et_password.setHint("密码不能为空");
            Utils.editViewValueErrorAnimate(et_password, context);
            et_password.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }

        if (password.length() < 6) {
            showToast(btn_register, "密码长度不足6位");
            Utils.editViewValueErrorAnimate(et_password, context);
            et_password.setPadding(Utils.dpToPx(90, context), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }


        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setUsername(name);
        presenter.register(user, mobileCode);

    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EaseConstant.REQUEST_CODE_PICK_AVATAR:

                    if (data != null) {
                        // TODO: 2019/7/4
                        selectedPhotos = null;
                        UCrop.Options options = new UCrop.Options();
                        options.setCircleDimmedLayer(true);
                        options.setToolbarColor(ResourcesCompat.getColor(getResources(), R.color.common_top_bar_blue, null));
                        options.setStatusBarColor(ResourcesCompat.getColor(getResources(), R.color.common_black, null));
                        UCrop.of(selectedPhotos.get(0), Uri.parse(path))
                                .withAspectRatio(1, 1)
                                .withMaxResultSize(480, 480)
                                .withOptions(options)
                                .start(this, EaseConstant.REQUEST_CODE_CROP);
                    }
                    break;

            }
        }
    }


    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void setPresenter(RegisterContrack.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showRegisterSuccess() {
        setResult(RESULT_OK);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
               finish();
            }
        }, 1500);
    }

    @Override
    public void showRegisterFail() {
        et_mobileCode.setTextColor(Color.RED);
    }

    @Override
    public void showSendMobileCodeSuccess() {

    }

    @Override
    public void setSendMobileCodeButtonText(final String count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_sendMobileCode.setText(count);
            }
        });
    }

    @Override
    public void showSendMobileCodeFail() {
        et_phone.setTextColor(Color.RED);
    }

    @Override
    public void showToast(String message) {
        super.showToast(btn_register, message);
        // Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        //Snackbar.make(container, message, Snackbar.LENGTH_INDEFINITE).show();
    }

    @Override
    public void showRetrievePassWord() {

    }

    @Override
    public void showProgressDialog(String message) {
        progressDialog.setMessage(message);
        progressDialog.show();
    }


    @Override
    public void disMissProgressDialog() {
        progressDialog.dismiss();
    }

    @Override
    public void showValiueEmputy(int viewId) {

    }


    @Override
    public void setSendMobileCodeButtonStatus(final boolean bool) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_sendMobileCode.setEnabled(bool);
            }
        });
    }

    @Override
    public void setRegisterButtonStatus(boolean bool) {
        btn_register.setEnabled(bool);
    }

    public void initProgressDialog() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }





    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length >= 1) {
                int writeResult = grantResults[0];
                //读写内存权限
                boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读内存权限

                if (writeGranted) {
                } else {
                    showToast("请到设置-权限管理中开启");
                }
            }
        }
    }

}

